import { useState, useCallback, useEffect } from "react";
import Choice from "../items/Choice";
import "./Talk.scss";

export default function Talk(props) {
  const { dialog, styleOpt, handleState, endState } = props;

  const [state, setState] = useState(false);
  const [name, setName] = useState("FIRST_DIALOG");
  const [text, setText] = useState(dialog[name][0]);
  const [index, setIndex] = useState(0);

  const handleText = useCallback(() => {
    const text = dialog[name][index + 1];
    if (text === "END") {
      handleState(endState);
    } else if (text[0] === "C") {
      setName(text.slice(2));
      setIndex(0);
      setState(true);
    } else if (text[0] === "V") {
      setName(text.slice(2));
      setIndex(0);
    } else if (!state) {
      setIndex((index) => index + 1);
    }
  }, [dialog, name, index, state, endState, handleState]);

  const handleChoice = useCallback((name) => {
    setName(name);
    setState(false);
  }, []);

  useEffect(() => {
    console.log(state);
    if (!state) {
      setText(dialog[name][index]);
    }
  }, [name, index, dialog, state]);

  return (
    <div className="talk">
      <header></header>
      <main>
        <div
          onClick={handleText}
          class="talk-text"
          style={{
            "text-shadow": "0 0 10px" + styleOpt.textColor,
            color: styleOpt.textColor,
          }}
        >
          {text}
        </div>
      </main>
      <footer>
        {state && (
          <Choice handleChoice={handleChoice} selection={dialog[name]} />
        )}
      </footer>
    </div>
  );
}
